<?php

namespace Muyuxuanpay\pay\common;

use Muyuxuanpay\tool\Mtool;

trait Tool
{
    protected $config;//配置
    protected $validateConfig=[];//验证配置
    protected $model;//模型
    protected $message='';
    public function getMessage(){
        return $this->message;
    }

    /**
     * 验证码需要的配置
     * @param array|null $data
     * @return string|true
     */
    public function validate(?array $data){
        if(!empty($data)){
            foreach ($this->config as $k=>$v){
                if(in_array($k,$data)){
                    if(empty($v)){
                        throw new \Exception("{$k}不能为空");
//                        return "{$k}不能为空";
                    }
                }
            }
        }
        return true;
    }

    /**
     * 获取订单号
     * @param string|null $userId
     * @param string|null $prefix
     * @param string|null $suffix
     * @param int|null $length
     * @return string
     */
    public function getOrderNo(?string $userId,?string $prefix,?string $suffix,?int $length=null){
        if(empty($length)){
            $length = 18;
        }
        $orderNo =  Mtool::getOrderNum($length,$userId,$prefix);
        if(empty($suffix)){
            $orderNo = $orderNo.$suffix;
        }
        return $orderNo;
    }
    public function log($message){
        if(empty($message)){
            return;
        }
        if(is_array($message)){
            $message = json_encode($message,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        }
        $message = date('Y-m-d H:i:s')." {$message}".PHP_EOL;
        $log_config = include __DIR__.'/../config/log.php';
        if(empty($log_config['debug'])){
           return false;
        }
        $fileDir = empty($log_config['fileDir'])?'/../../log/':$log_config['fileDir'];
        $fileName = __DIR__.$fileDir.date('Y-m-d').'.log';
        if(!is_file($fileName)){
            if(!is_dir(dirname($fileName))){
                mkdir(dirname($fileName),0777,true);
            }
            file_put_contents($fileName,'',FILE_APPEND);
            chmod($fileName,0777);
        }
        file_put_contents($fileName,$message,FILE_APPEND);
    }
}